<?php
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\User;
use app\admin\model\User as UserModel;
use app\admin\model\Group as GroupModel;
use think\Cache;
use think\facade\Db;
use app\admin\model\LoginRecord;
use app\crm\traits\StarTrait;
use com\verify\Sms as TpSms;
use app\admin\model\File as FileModel;
use think\response\Json;


class Users extends ApiCommon
{
    use StarTrait;

    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录员工可访问
     * @other 其他根据系统设置
     **/
    public function initialize()
    {
        $action = [
            'permission' => ['exceldownload', 'forgetpassword', 'setpassword', 'selectparent','getpwdrule'],
            'allow' => ['updateimg', 'all','center']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }

    /**
     * 员工列表
     * @return Json
     * @author Mr.Li
     * @create 2021-06-05 11:47
     */
    public function index()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $data = $userModel->getDataList($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 员工详情
     * @return Json
     * @author Mr.Li
     * @create 2021-06-05 11:47
     */
    public function read()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $userInfo = $this->userInfo;
        if (!isset($param['id']) || !$param['id']) $param['id'] = $userInfo['id'];
        $data = $userModel->getDataById($param['id']);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 员工创建
     * @return Json
     * @author Mr.Li
     * @create 2021-06-05 11:47
     */
    public function save()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $data = $userModel->createData($param);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['data' => [], 'error' => '创建成功']);
    }

    /**
     * 员工编辑
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Li
     * @create 2021-06-05 11:47
     */
    public function update()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $userInfo = $this->userInfo;
        $userData = Db::name('admin_user')->where(['id' => $param['id']])->find();
        if (!$param['id']) {
            //修改个人信息
            $param['user_id'] = $userInfo['id'];
        } else {
            //权限判断
            if (!checkPerByAction('admin', 'users', 'update')) {
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode(['code' => 102, 'error' => '无权操作']));
            }
        }
        //unset($param['username']);
        $data = $userModel->updateDataById($param, $param['id']);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['data' => [], 'error' => '编辑成功']);
    }

    //批量设置密码
    public function updatePwd()
    {
        //权限判断
        if (!checkPerByAction('admin', 'users', 'update')) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }
        $param = $this->param;
        if ($param['password'] && is_array($param['id'])) {
            $userModel = model('User');
            $ret = $userModel->updatePwdById($param);
            if ($ret) {
                return resultArray(['data' => true]);
            } else {
                return resultArray(['error' => $userModel->getError()]);
            }
        } else {
            return resultArray(['error' => '参数错误']);
        }
    }

    /**
     * 更新员工状态
     * @param UserModel $userModel
     * @return Json
     * @author Mr.Liu Wuchen
     * @create 2021-07-31 16:20
     */
    public function enables(UserModel $userModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $userModel->updateStatusData($this->param);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['error' => $userModel->getError(), 'data' => []]);
    }

    /**
     * 获取权限范围内的员工数组
     * @param
     * @return
     */
    public function getUserList()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $by = $param['by'] ?? '';
        $user_id = $param['user_id'] ?? '';
        $where = [];
        $belowIds = [];
        $param['m'] = $param['m'] ?? '';
        $param['c'] = $param['c'] ?? '';
        $param['a'] = $param['a'] ?? '';
        if ($param['m'] && $param['c'] && $param['a']) {
            if ($param['m'] == 'oa' && $param['c'] == 'task') {
                $belowIds = getSubUserId(true, 1);
            } else {
                $belowIds = $userModel->getUserByPer($param['m'], $param['c'], $param['a']);
            }
            $where[] = ['user.id', 'in', $belowIds];
        } else {
            if ($by == 'sub') {
                $userInfo = $this->userInfo;
                $adminIds = $userModel->getAdminId();
                if (in_array($userInfo['id'], $adminIds)) {
                    $belowIds = getSubUserId(true, 1);
                } else {
                    //下属id
                    $belowIds = getSubUserId();
                }
                $where[] = ['user.id', 'in', $belowIds];
            } elseif ($by == 'parent') {
                if ($user_id == 1) {
                    $where[] = ['user.id', '=', 0];
                } else {
                    $unUserId[] = $user_id;
                    $subUserId = getSubUser($user_id);
                    $unUserId = $subUserId ? array_merge($subUserId, $unUserId) : $unUserId;
                }
                $where[] = ['user.id', 'not in', $unUserId];
            } else {
                $belowIds = getSubUserId(true, 1);

                if ($belowIds) {
                    $belowIds = implode(',', $belowIds);
                } else {
                    $belowIds = 0;
                }

                $where[] = ['user.id', 'in', $belowIds];
            }
        }
        $userList = Db::name('admin_user')
            ->alias('user')
            ->where($where)
            ->where('user.status>0 and user.type=1')
            ->join('admin_structure structure', 'structure.id = user.structure_id', 'LEFT')
            ->field('user.id,user.realname,user.thumb_img,structure.name as s_name')
            ->select()->toArray();


        # 角色数据
        $groupList = Db::name('admin_access')->alias('access')
            ->join('admin_group group', 'group.id = access.group_id', 'LEFT')
            ->field('group.id, group.title, access.user_id')->select()->toArray();
        $groupArray = [];
        foreach ($groupList as $key => $value) {
            $groupArray[$value['user_id']]['roleId'][] = $value['id'];
            $groupArray[$value['user_id']]['roleName'][] = $value['title'];
        }

        foreach ($userList as $k => $v) {
            $userList[$k]['username'] = $v['realname'];
            $userList[$k]['thumb_img'] = $v['thumb_img'] ? getFullPath($v['thumb_img']) : '';

            # 员工新增角色ID和角色名称字段
            $userList[$k]['roleId'] = !empty($groupArray[$v['id']]['roleId']) ? implode(',', $groupArray[$v['id']]['roleId']) : '';
            $userList[$k]['roleName'] = !empty($groupArray[$v['id']]['roleName']) ? implode(',', $groupArray[$v['id']]['roleName']) : '';
            # 单独处理admin管理员的角色ID和角色名称字段
            if ($v['id'] == 1 && (empty($groupArray[$v['id']]['roleId']) || empty($groupArray[$v['id']]['roleName']))) {
                $userList[$k]['roleId'] = '1';
                $userList[$k]['roleName'] = '超级管理员角色';
            }
        }
        return resultArray(['data' => $userList ?: []]);
    }

    /**
     * 修改头像
     * @param
     * @return
     */
    public function updateImg()
    {

        $userInfo = $this->userInfo;
        $param = $this->param;
        $param['create_user_id'] = $this->userInfo['id'];
        if (empty($param['thumb_img'])) {
            return resultArray(['error' => '头像路径不能为空']);
        }
        $param['thumb_img'] = str_replace(config('app.img_url'),'',$param['thumb_img']);
        $param['thumb_img'] = str_replace(config('app.http_img_url'),'',$param['thumb_img']);
        $userModel = new UserModel();
        $data = $userModel->updateImg($this->userInfo['id'], $param['thumb_img']);
        return resultArray(['data' => [], 'error' => '更换成功']);


    }

    /**
     * 重置密码
     * @param
     * @return
     */
    public function resetPassword()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        if (!isset($param['id'])) {
            return resultArray(['error' => '请选择用户！']);
        }

        if ($param['id'] && (int)$param['id'] !== $userInfo['id']) {
            if ($param['id'] == 1) {
                return resultArray(['error' => '不能重置超管密码']);
            }
            $user_id = $param['id'];
            $userModel = new UserModel();
            $userInfo = $userModel->getDataById($user_id, 'id,username,password,salt');
            $param['new_pwd'] = (new \app\admin\model\Password())->getDefaultPwd();
            if (Db::name('admin_user')->where('id', $user_id)->update(['password' => user_md5($param['new_pwd'], $userInfo['salt'], $userInfo['username'])]) >= 0) {
                return resultArray(['data' => [], 'error' => '密码重置成功']);
            } else {
                return resultArray(['error' => '密码重置失败']);
            }
        } else {

            $userModel = new UserModel();
            $data = $userModel->updatePaw($userInfo, '', '');
            if (!$data) {
                return resultArray(['error' => $userModel->getError()]);
            }
            return resultArray(['data' => [], 'error' => '密码重置成功']);
        }
    }


    /**
     * 用户设置密码
     * @param
     * @return
     */
    public function setPassword()
    {
        $param = request()->param();
        $userInfo = $this->userInfo;
        if (empty($param['new_pwd']) || empty($param['old_pwd'])) return resultArray(['error' => '密码不能为空！']);
        if (!$userInfo) {
            if (!isset($param['id'])) {
                return resultArray(['error' => '请选择用户！']);
            }
            $userModel = new UserModel();
            $userInfo = $userModel->getDataById($param['id'], 'id,username,password,salt,status');

        }

        $old_pwd = $param['old_pwd'];
        $new_pwd = $param['new_pwd'];
        $data = $userModel->updatePaw($userInfo, $old_pwd, $new_pwd, 1);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }

        //成功修改密码需要删除修改密码标识
        if(\think\facade\Cache::has('is_first_login:'.$userInfo['id'])){//删除修改密码记录
            \think\facade\Cache::delete('is_first_login:'.$userInfo['id']);
        }
        return resultArray(['data' => [], 'error' => '修改成功']);

    }


    /**
     * 忘记密码
     * @param
     * @return
     */
    public function forgetPassword()
    {
        $param = input();
        if (empty($param['mobile'])) return resultArray(['error' => '请输入手机号！']);
        $userModel = new UserModel();
        $userInfo = $userModel->getDataByMobile($param['mobile']);
        if (!$userInfo) {
            //$this->error = '密码没改变';
            return resultArray(['error' => $userModel->getError()]);
        }
        //短信验证码校验
        // $tpSms = new TpSms(['scene' => 1]);
        // if (!$tpSms->check()) {

        //     //验证失败，获取失败信息
        //     return resultArray(['error' => $tpSms->getErrorMsg()]);
        // }
        // $tpSms = new TpSms(['scene' => 1]);
        // if (!$tpSms->check()) {

        //     //验证失败，获取失败信息
        //     return resultArray(['error' => $tpSms->getErrorMsg()]);
        // }
        $where = [];
        $time  = time()-15*60;
        $code    = $param['code'] ?? 0;
        $phone   = $param['mobile'] ?? 0;
        array_push($where,['code','=',$code]);
        array_push($where,['phone','=',$phone]);
        array_push($where,['type','=',2]);
        array_push($where,['create_time','>=',$time]);
        $res = Db::name('phone_code')->where($where)->find();
        if (!$res) {
          return resultArray(['error' => '验证码错误']);
        }
        //重新设置新密码
        if (!empty($param['newPwd']) && !empty($param['confirmNewPwd'])) {
            /*
            if(empty($param['verify_code'])){
                return resultArray(['error' => '图形验证码不能为空']);
            }
            */
            if ($param['newPwd'] != $param['confirmNewPwd']) {
                return resultArray(['error' => '两次密码不一致']);
            }


            $updData = [
                'id' => $userInfo['id'],
                'password' => user_md5($param['newPwd'], $userInfo['salt'], $userInfo['username']),
                // 'verify_code'       => $param['verify_code']
            ];

            //检测密码设置
            $pwdRuleObj = new \app\admin\model\Password();
            $pwdRuleMsg = $pwdRuleObj->checkPwd($userInfo['username'], $userInfo['password'], $updData['password'], $param['newPwd']);
            if ($pwdRuleMsg) {
                return resultArray(['error' => $pwdRuleMsg]);
            }
            if ($userModel->forgetPassword($updData)) {
                return resultArray(['data' => [], 'error' => '密码重置成功']);
            } else {
                return resultArray(['error' => $userModel->getError()]);
            }
        }
        return resultArray(['error' => '请输入密码']);


    }


    /**
     * 员工角色关系
     * @param
     * @return
     */
    public function groups()
    {
        //权限判断
        if (!checkPerByAction('admin', 'groups', 'update')) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }
        $param = $this->param;
        if (!$param['users'] && !$param['structures']) {
            return resultArray(['error' => '请选择员工']);
        }
        if (!$param['groups']) {
            return resultArray(['error' => '请选择角色']);
        }
        $userModel = model('User');
        //部门下所有员工
        $userArr = [];
        if (is_array($param['structures'])) {
            foreach ($param['structures'] as $v) {
                $userArr[] = $userModel->getSubUserByStr($v);
            }
        }
        if ($userArr) $userArr = call_user_func_array('array_merge', $userArr); //数组合并
        if ($userArr && $param['users']) {
            $userIds = array_merge($userArr, $param['users']);
        } elseif ($userArr) {
            $userIds = $userArr;
        } else {
            $userIds = $param['users'];
        }
        $userIds = array_unique($userIds);
        $groups = $param['groups'];
        $accessModel = model('Access');
        $resData = true;
        foreach ($userIds as $k => $v) {
            //角色员工关系处理
            $res = $accessModel->userGroup($v, $param['groups']);
            if (!$res) {
                $resData = false;
            }
        }
        // if ($resData == false) {
        //     return resultArray(['error' => '操作失败，请重试']);
        // }
        return resultArray(['data' => '创建成功']);
    }

    /**
     * 员工角色关系（删除）
     * @param
     * @return
     */
    public function groupsDel()
    {
        //权限判断
        if (!checkPerByAction('admin', 'groups', 'update')) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }
        $param = $this->param;
        if (!$param['user_id']) {
            return resultArray(['error' => '请选择员工']);
        }
        if (!$param['group_id']) {
            return resultArray(['error' => '参数错误']);
        }

        # 员工至少保留一个角色
        $count = db('admin_access')->where(['user_id' => $param['user_id']])->count();
        if ($count == 1) return resultArray(['error' => '员工至少保留一个角色！']);

        $res = db('admin_access')->where(['user_id' => $param['user_id'], 'group_id' => $param['group_id']])->delete();
        if (!$res) {
            return resultArray(['error' => '操作失败，请重试']);
        }
        return resultArray(['data' => '删除成功']);
    }

    /**
     * [structureUserList 部门员工混合数据]
     * @param
     * @return
     */
    public function structureUserList()
    {
        $structure_list = db('admin_structure')->select();
        $structureList = getSubObj(0, $structure_list, '', 1);
        foreach ($structureList as $k => $v) {
            $userList = [];
            $userList = db('admin_user')->where(['structure_id' => $v['id'], 'status' => array('in', ['1', '3'])])->field('id,realname')->select();
            $structureList[$k]['userList'] = $userList;
        }
        return $structureList;
    }

    //人资员工导入
    public function tobeusers()
    {
        $userModel = model('User');
        $param = $this->param;
        $flag = $userModel->beusers($param);
        if ($flag) {
            return resultArray(['data' => $flag]);
        } else {
            return resultArray(['error' => $userModel->getError()]);
        }
    }

    //根据部门ID获取员工列表
    public function userListByStructId()
    {
        $usermodel = model('User');
        $param = $this->param;
        $structure_id = $param['structure_id'] ?: '';
        $ret = $usermodel->getUserListByStructureId($structure_id) ?: [];
        return resultArray(['data' => $ret]);
    }

    /**
     * 员工账号修改
     * @param
     * @return
     */
    public function usernameEdit()
    {
        //权限判断
        if (!checkPerByAction('admin', 'users', 'update')) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }
        $param = $this->param;
        $userInfo = $this->userInfo;
        //权限判断
        if ($param['id'] == 1) {
            return resultArray(['error' => '管理员账号暂不能修改']);
        }
        $adminTypes = adminGroupTypes($userInfo['id']);
        if (!in_array(3, $adminTypes) && !in_array(1, $adminTypes) && !in_array(2, $adminTypes)) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }
        if (!$param['id'] || !$param['username'] || !$param['password']) {
            return resultArray(['error' => '参数错误！']);
        }
        if (db('admin_user')->where(['id' => ['neq', $param['id']], 'username' => $param['username']])->find()) {
            return resultArray(['error' => '手机号码已存在！']);
        }
        $userData = db('admin_user')->where(['id' => $param['id']])->field('username,salt,password')->find();
        $data = [];
        $data['username'] = $param['username'];
        $data['password'] = user_md5($param['password'], $userData['salt'], $param['username']);
        $data['userInfo'] = $userData;
        $data['mobile'] = $param['username'];
        $resSync = model('Sync')->syncData($data);
        if ($resSync) {
            unset($data['userInfo']);
            $res = db('admin_user')->where(['id' => $param['id']])->update($data);
            return resultArray(['data' => '修改成功！']);
        } else {
            return resultArray(['error' => '修改失败，请重试！']);
        }
    }

    /**
     * 登录记录
     */
    public function loginRecord()
    {
        if (!checkPerByAction('admin', 'loginRecord', 'index')) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 102, 'error' => '无权操作']));
        }

        $loginRecordModel = new LoginRecord();
        $where = [];
        getWhereUserByParam($where, 'create_user_id');
        getWhereTimeByParam($where, 'create_time');

        $limit = $this->param['limit'] ?: 15;
        $data = $loginRecordModel
            ->where($where)
            ->order(['create_time' => 'DESC'])
            ->paginate($limit)
            ->each(function ($val) {
                $val['username'] = $val->create_user_info['realname'];
                $val['type_name'] = $val->type_name;
            })
            ->toArray();
        return resultArray([
            'data' => [
                'list' => $data['data'],
                'dataCount' => $data['total']
            ],
        ]);
    }

    /**
     * 员工导入模板下载
     * @param string $save_path 本地保存路径     用于错误数据导出，在 Admin\Model\Excel::batchImportData()调用
     * @return
     * @author Mr.Li
     */
    public function excelDownload($save_path = '')
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $excelModel = new \app\admin\model\Excel();

        // 导出的字段列表
        $field_list = UserModel::$import_field_list;
        $excelModel->excelImportDownload($field_list, 'admin_user', $save_path);
    }

    /**
     * 员工导入
     */
    public function import()
    {
        if (empty($_FILES['file'])) {
            return resultArray(['error' => '文件不存在！']);
        }
        $filename = $_FILES['file']['name'];
        $tmp_name = $_FILES["file"]["tmp_name"];
        if (empty($tmp_name) || !file_exists($tmp_name)) {
            return resultArray(['error' => '文件不存在！']);
        }

        $importData = readExcelData($tmp_name);
        $userModel = new UserModel();
        $res = $userModel->createBatchData($importData);
        if (!$res) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['data' => $importData, 'error' => '导入成功']);
    }

    /**
     * 批量设置直属上级
     */
    public function setParent()
    {
        // 仅允许超管，系统管理员，部门与员工管理员 批量设置
        if (false === UserModel::checkUserGroup([1, 2, 3])) {
            return resultArray(['error' => '没有该权限']);
        }
        $parent_id = (int)$this->param['parent_id'];
        $parent_user = UserModel::find($parent_id);
        if (!$parent_user) {
            return resultArray(['error' => '请选择直属上级']);
        }
        $user_id_list = (array)$this->param['id_list'];
        if (empty($user_id_list)) {
            return resultArray(['error' => '请选择员工']);
        }
        if (in_array(1, $user_id_list)) {
            return resultArray(['error' => '超级管理员不能设置上级']);
        }

        if (in_array($parent_id, $user_id_list)) {
            return resultArray(['error' => '直属上级不能为员工自己']);
        }

        foreach ($user_id_list as $val) {
            if (in_array($parent_id, getSubUserId(true, 0, (int)$val))) {
                return resultArray(['error' => '直属上级不能是自己下属（包含下属的下属）']);
            }
        }

        $a = new \think\facade\Model;
        if ($a->where(['id' => ['IN', $user_id_list]])->update(['parent_id' => $parent_id])) {
            Cache::clear('user_info');
            return resultArray(['data' => '员工直属上级设置成功']);
        } else {
            return resultArray(['error' => '员工直属上级设置失败' . $a->getError()]);
        }
    }

    /**
     * 通讯录列表
     * @return mixed
     */
    public function queryList()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $userLogic = new UserLogic();
        $data = $userLogic->getDataList($param);
        return resultArray(['data' => $data]);

    }

    /**
     * 关注的通讯录列表
     * @return mixed
     */
    public function starList()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $userLogic = new UserLogic();
        $data = $userLogic->queryList($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 设置关注
     *
     */
    public function userStar()
    {
        $userInfo = $this->userInfo;
        $userId = $userInfo['id'];
        $targetId = $this->param['target_id'];
        $type = $this->param['type'];

        if (empty($userId) || empty($targetId) || empty($type)) return resultArray(['error' => '缺少必要参数！']);

        if (!$this->setStar($type, $userId, $targetId)) {
            return resultArray(['error' => '设置关注失败！']);
        }

        return resultArray(['data' => '设置关注成功！']);
    }

    /**
     * 复制员工角色
     *
     * @return Json
     */
    public function copyRole()
    {
        $param = $this->param;

        if (empty($param['user_id']) && empty($param['structure_id'])) return resultArray(['error' => '请选择员工或部门！']);
        if (empty($param['group_id'])) return resultArray(['error' => '请选择角色！']);

        $userModel = new UserModel();

        if (!$userModel->copyRole($param)) return resultArray(['error' => '操作失败！']);

        return resultArray(['data' => '操作成功！']);
    }

    /**
     * 获取下属（全部层级）
     *
     */
    public function subordinate()
    {
        $userId = $this->userInfo['id'];

        # 获取下属的ID
        $subIds = getSubUserId(false, 0, $userId);

        $data = Db::name('admin_user')->field(['id', 'realname', 'thumb_img as img'])->whereIn('id', $subIds)->select();

        foreach ($data as $key => $value) {
            $data[$key]['img'] = !empty($data[$key]['img']) ? getFullPath($data[$key]['img']) : '';
        }

        return resultArray(['data' => $data]);
    }

    /**
     * 获取当前登录人信息
     *
     */
    public function queryLoginUser()
    {
        $resData = [];
        $wkcode = file_get_contents(CONF_PATH . 'license.dat');
        if ($wkcode) {
            $resCheckData = checkWkCode($wkcode);
            if ($resCheckData) {
                $resData = object_to_array(json_decode($resCheckData));
            }
        }
        return $resData;
    }


    /**
     * 用户角色列表
     * @param
     * @return
     * @author Mr.Li
     */
    public function groupIndex()
    {
        $groupModel = new GroupModel();
        $param = $this->param;
        $data = $groupModel->getDataList($param);
        return resultArray(['data' => $data]);
    }


    /**
     * 所有员工列表
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Li
     * @create 2021-07-07 15:43
     */

    public function all()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $data = $userModel->all($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 解锁账号密码锁定
     * @return Json
     * @author Mr.Li
     * @create 2021-07-30 17:11
     */

    public function unlockAccountPassword()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $id = $param['id'] ?? 0;
        if (!$id) {
            return resultArray(['error' => '用户id不能为空']);
        }
        $data = $userModel->unlockAccountPassword($id);
        if ($data) {
            return resultArray(['data' => [], 'error' => '解锁成功']);
        }
        return resultArray(['error' => $userModel->getError()]);
    }

    /**
     * 批量选择上级
     * @param UserModel $userModel
     * @return Json
     * @author Mr.Liu Wuchen
     * @create 2021-07-31 16:45
     */
    public function selectParent(UserModel $userModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $userModel->getSelectParentData($this->param);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['error' => $userModel->getError(), 'data' => $data['data']]);
    }

    /**
     * 批量更新直属上级
     * @param UserModel $userModel
     * @return Json
     * @author Mr.Liu Wuchen
     * @create 2021-07-31 16:20
     */
    public function parent(UserModel $userModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $userModel->updateParentData($this->param);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['error' => $userModel->getError(), 'data' => []]);

    }


    /**
     * 个人中心(app)
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Li
     * @create 2021-08-02 14:39
     */
    public function center()
    {
        $userModel = new UserModel();
        $param = $this->param;
        $userInfo = $this->userInfo;
        if (!isset($param['id']) || !$param['id']) $param['id'] = $userInfo['id'];
        $data = $userModel->center($param['id']);
        if (!$data) {
            return resultArray(['error' => $userModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 获取密码策略
     * @return Json
     * @author Mr.Li
     * @create 2021-08-31 16:32
     */
    public function getPwdRule()
    {
        $ruleMsg = '';
        $passwordRuleObj = new \app\admin\model\Password();
        $pwdData = $passwordRuleObj->getDataList();
        if($pwdData){
            $ruleMsg = $passwordRuleObj->checkPwdRule($pwdData,'');
        }
        return resultArray(['data' => ['rule_msg' => $ruleMsg]]);
    }

    /**
     * 更新员工部门id
     * @return Json
     * @author lilongfei
     * @date 2021-09-11 15:50
     */
    public function updateUserStructId( UserModel $userModel)
    {
        if (empty($_FILES['file'])) {
            return resultArray(['error' => '文件不存在！']);
        }
        $filename = $_FILES['file']['name'];
        $tmp_name = $_FILES["file"]["tmp_name"];
        if (empty($tmp_name) || !file_exists($tmp_name)) {
            return resultArray(['error' => '文件不存在！']);
        }

        $importData = readExcelData($tmp_name);

        if($userModel->updateUserStructId($importData)){
            return resultArray(['data' => [], 'error' => '更新成功']);
        }
        return resultArray(['error' => $userModel->getError()]);

    }

}
